﻿using System;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Windows.Forms;
using PPI.Client;
using PPI.Client.Logic.Distribution;
using PPI.Client.Utils;
using PPI.Entities.Distribution;
using PPI.Entities.XML;
using PPI.General;
using Cursors=System.Windows.Forms.Cursors;
using KeyEventArgs=System.Windows.Forms.KeyEventArgs;
using Keys=System.Windows.Forms.Keys;
using OpenFileDialog=System.Windows.Forms.OpenFileDialog;

namespace PPI.CRUD
{
    public partial class frmDistributionSectionalizerEditor : frmBase
    {
        public ESectionalizer Sectionalizer { get; set; }
        public EDistributionPole Pole { get; set; }
        public EXmlOutboxBase m_OutboxBase { get; set; }       
        
        
        public frmDistributionSectionalizerEditor()
        {
            InitializeComponent();
        }

        public void LoadControls()
        {
            string selectOption = "Select an option ...";
            
            DropdownHelper.FillDropdown(ddlPhase, GetLookUps(DistributionLookUpType.Phase), selectOption);
            DropdownHelper.FillDropdown(ddlPCBType, GetLookUps(DistributionLookUpType.PCBType), selectOption);
            DropdownHelper.FillDropdown(ddlDeterminedBy, GetLookUps(DistributionLookUpType.DeterminedBy), selectOption);
            DropdownHelper.FillDropdown(ddlInterrupter, GetLookUps(DistributionLookUpType.Interrupter), selectOption);

            DropdownHelper.FillLengthDropDown(ddlCurveA, 0, 9, 1, selectOption);
            DropdownHelper.FillLengthDropDown(ddlCurveB, 0, 9, 1, selectOption);
            DropdownHelper.FillLengthDropDown(ddlCurveC, 0, 9, 1, selectOption);
            DropdownHelper.FillLengthDropDown(ddlCurveD, 0, 9, 1, selectOption);

            lstNotes.DataSource = GetLookUps(DistributionLookUpType.Keyword);
        }

        public void LoadSectionalizer()
        {
            lblVisualInspection.Text = Sectionalizer.CreatedDate.ToString("MM/dd/yyyy");
            txtSerialNumber.Text = Sectionalizer.SerialNumber;
            txtMenufacturer.Text = Sectionalizer.Manufacturer;
            txtCondition.Text = Sectionalizer.Comments;
            txtPPM.Text = Sectionalizer.PPM;
            txtTransformerNumber.Text = Sectionalizer.PoleNumber;
            txtTestNumber.Text = Sectionalizer.TestNumber;
            txtMaxkV.Text = Sectionalizer.MaxkV;
            txtType.Text = Sectionalizer.Type;

            if (Sectionalizer.ManufDate == DateTime.MinValue)
            {
                checkBoxX1.Checked = false;
            }
            else
            {
                checkBoxX1.Checked = true;
                dtpManufDate.Value = Sectionalizer.ManufDate;
            }

            chkPre1978.Checked = Sectionalizer.Pre1978;
            chkSticker.Checked = Sectionalizer.Sticker;

            ddlPhase.SelectedItem = Sectionalizer.Phase;
            ddlPCBType.SelectedItem = Sectionalizer.PCBType;
            ddlDeterminedBy.SelectedItem = Sectionalizer.DeterminedBy;
            ddlInterrupter.SelectedItem = Sectionalizer.Interrupter;

            if (Sectionalizer.CurveA != Int32.MinValue)
                ddlCurveA.SelectedIndex = DropdownHelper.GetItemIndex(ddlCurveA, Sectionalizer.CurveA.ToString());

            if (Sectionalizer.CurveB != Int32.MinValue)
                ddlCurveB.SelectedIndex = DropdownHelper.GetItemIndex(ddlCurveB, Sectionalizer.CurveB.ToString());

            if (Sectionalizer.CurveC != Int32.MinValue)
                ddlCurveC.SelectedIndex = DropdownHelper.GetItemIndex(ddlCurveC, Sectionalizer.CurveC.ToString());

            if (Sectionalizer.CurveD != Int32.MinValue)
                ddlCurveD.SelectedIndex = DropdownHelper.GetItemIndex(ddlCurveD, Sectionalizer.CurveD.ToString());
            
            position1.SetLatitude(Sectionalizer.Latitude == double.MinValue ? 0 : Sectionalizer.Latitude);
            position1.SetLongitude(Sectionalizer.Longitude == double.MinValue ? 0 : Sectionalizer.Longitude);

            lstNotes.ClearSelected();
            foreach (var note in Sectionalizer.Notes)
            {
                //top.Key = top.Id.ToString();
                lstNotes.SetSelected(lstNotes.Items.IndexOf(note), true);
            }
        }

        private EDistributionLookUp[] GetLookUps(DistributionLookUpType type)
        {
            return LCacheDistributionDataSingleton.Instance.DistributionLookUps.Where(x => x.Type == type).ToArray();
        }


        private void lstImages_KeyDown(object sender, KeyEventArgs e)
        {
            try
            {
                if (e.KeyCode == Keys.Delete)
                {
                    if (lstImages.SelectedIndex > -1)
                    {
                        //Transformer.Image = new EDistributionPoleImage();
                        LoadImages();

                        if (lstImages.Items.Count == 0)
                            btnSearchImage.Enabled = true;
                    }
                }
            }
            catch (Exception ex)
            {
                RegisterError.SaveError(ex);
            }
        }

        private void LoadImages()
        {
            pbxSelectedImage.Image = null;

            lstImages.DataSource = null;
            lstImages.Items.Clear();

            lstImages.DataSource = Sectionalizer.Images;
            lstImages.DisplayMember = "Title";

            /*if (lstImages.Items.Count > 0)
                btnSearchImage.Enabled = false;*/
        }

        private void lstImages_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                if (lstImages.SelectedIndex > -1)
                {
                    var tmpImage = (EDistributionPoleImage)lstImages.SelectedItem;

                    viewImage(tmpImage);
                }
            }
            catch (Exception ex)
            {
                RegisterError.SaveError(ex);
            }
        }

        private void viewImage(EDistributionPoleImage image)
        {
            FileInfo meterImage;

            if (!Pole.isProjectPole)
            {
                if (image.Id == Int32.MinValue)
                    meterImage = new FileInfo(image.FullName);
                else
                    meterImage = new FileInfo(DirHelper.GetImagesDirectory(m_OutboxBase.ConnectionString) + Path.DirectorySeparatorChar + image.FileName);
            }
            else
            {
                meterImage = new FileInfo(image.GetTemporaryFolder());
            }

            if (meterImage.Exists)
            {
                using (Stream s = File.OpenRead(meterImage.FullName))
                    pbxSelectedImage.Image = Image.FromStream(s);
            }
            else
                pbxSelectedImage.Image = null;
        }

        private void frmDistributionTransformerEditor_Load(object sender, EventArgs e)
        {
            LoadControls();
            LoadSectionalizer();
            LoadImages();

            tabMain.SelectedTab = tabMainSectionalizer;

            if (lstImages.Items.Count > 0)
                lstImages.SelectedIndex = 0;
            else
            {
                btnSearchImage.Enabled = true;
                pbxSelectedImage.Image = null;
            }
        }


        private void btnSave_Click(object sender, EventArgs e)
        {
            SaveSectionalizer();
            Close();
        }

        private void SaveSectionalizer()
        {
            try
            {
                Cursor = Cursors.WaitCursor;
                ESectionalizer actualSectionalzier = Sectionalizer;
                /*
                if (lstImages.Items.Count > 0)
                    actualTransformer.Image = lstImages.Items[0] as EDistributionPoleImage;
                else
                    actualTransformer.Image = null;
                */
                actualSectionalzier.SerialNumber = txtSerialNumber.Text;
                actualSectionalzier.Manufacturer  = txtMenufacturer.Text;
                actualSectionalzier.Comments = txtCondition.Text;
                actualSectionalzier.PPM = txtPPM.Text;
                actualSectionalzier.TestNumber = txtTestNumber.Text;
                
                actualSectionalzier.MaxkV = txtMaxkV.Text;
                actualSectionalzier.Type = txtType.Text;
                actualSectionalzier.PoleNumber = txtTransformerNumber.Text;

                actualSectionalzier.Pre1978 = chkPre1978.Checked;
                actualSectionalzier.Sticker = chkSticker.Checked;
 
                actualSectionalzier.Phase = ddlPhase.SelectedItem as EDistributionLookUp;
                actualSectionalzier.PCBType = ddlPCBType.SelectedItem as EDistributionLookUp;
                actualSectionalzier.DeterminedBy = ddlDeterminedBy.SelectedItem as EDistributionLookUp;
                actualSectionalzier.Interrupter = ddlInterrupter.SelectedItem as EDistributionLookUp;

                if (checkBoxX1.Checked)
                    actualSectionalzier.ManufDate = dtpManufDate.Value;
                else
                    actualSectionalzier.ManufDate = DateTime.MinValue;

                if (ddlCurveA.SelectedIndex > 0)
                    actualSectionalzier.CurveA = Convert.ToInt32(((ListBoxItem)ddlCurveA.SelectedItem).Value);
                else
                    actualSectionalzier.CurveA = Int32.MinValue;

                if (ddlCurveB.SelectedIndex > 0)
                    actualSectionalzier.CurveB = Convert.ToInt32(((ListBoxItem)ddlCurveB.SelectedItem).Value);
                else
                    actualSectionalzier.CurveB = Int32.MinValue;

                if (ddlCurveC.SelectedIndex > 0)
                    actualSectionalzier.CurveC = Convert.ToInt32(((ListBoxItem)ddlCurveC.SelectedItem).Value);
                else
                    actualSectionalzier.CurveC = Int32.MinValue;

                if (ddlCurveD.SelectedIndex > 0)
                    actualSectionalzier.CurveD = Convert.ToInt32(((ListBoxItem)ddlCurveD.SelectedItem).Value);
                else
                    actualSectionalzier.CurveD = Int32.MinValue;

                actualSectionalzier.Latitude = position1.GetLatitude();
                actualSectionalzier.Longitude = position1.GetLongitude();

                actualSectionalzier.Notes.Clear();
                foreach (EDistributionLookUp note in lstNotes.SelectedItems)
                    actualSectionalzier.Notes.Add(note);

                actualSectionalzier.Images.Clear();
                foreach (EDistributionPoleImage image in lstImages.Items)
                    actualSectionalzier.Images.Add(image);

                LSectionalizer.Update(m_OutboxBase.ConnectionString, Pole, actualSectionalzier);
            }
            catch (Exception ex)
            {
                RegisterError.SaveError(ex);
            }
            finally
            {
                Cursor = Cursors.Default;
            }
        }

        private void btnSearchImage_Click(object sender, EventArgs e)
        {
            SearchImage();
        }

        private void SearchImage()
        {
            try
            {
                OpenFileDialog _OpenFileDialog = new OpenFileDialog();
                DialogResult _DialogResult = _OpenFileDialog.ShowDialog();

                switch (_DialogResult)
                {
                    case DialogResult.OK:
                    case DialogResult.Yes:
                        FileInfo selectedFile = new FileInfo(_OpenFileDialog.FileName);
                        var img = new EDistributionPoleImage();

                        img.ImageType = DistributionImageType.Transformer;
                        img.FullName = selectedFile.FullName;
                        img.FileName = "Unsaved " + Path.GetFileName(selectedFile.FullName);
                        
                        Sectionalizer.Images.Add(img);

                        LoadImages();
                        break;
                    default:
                        break;
                }
            }
            catch (Exception ex)
            {
                RegisterError.SaveError(ex);
            }
        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            Close();
        }

        private void checkBoxX1_CheckedChanged(object sender, EventArgs e)
        {
            dtpManufDate.Enabled = checkBoxX1.Checked;
        }
    }
}
